﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseComponent;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;


public partial class toc : System.Web.UI.Page
{

    public imsitemHierList mobjimsitemHierList
    {
        get
        {
            if (ViewState["mobjimsitemHierList"] == null)
                ViewState["mobjimsitemHierList"] = System.Guid.NewGuid().ToString();

            return Session[ViewState["mobjimsitemHierList"].ToString()] as imsitemHierList;


        }
        set
        {
            if (ViewState["mobjimsitemHierList"] == null)
                ViewState["mobjimsitemHierList"] = System.Guid.NewGuid().ToString();

            Session[ViewState["mobjimsitemHierList"].ToString()] = value;
        }
    }

    public Courses mObjCourses
    {
        get
        {
            if (ViewState["mObjCourses"] == null)
                ViewState["mObjCourses"] = System.Guid.NewGuid().ToString();

            return Session[ViewState["mObjCourses"].ToString()] as Courses;


        }
        set
        {
            if (ViewState["mObjCourses"] == null)
                ViewState["mObjCourses"] = System.Guid.NewGuid().ToString();

            Session[ViewState["mObjCourses"].ToString()] = value;
        }
    }


    public RegisteredCourses mobjRegisteredCourses
    {
        get
        {
            if (ViewState["mobjRegisteredCourses"] == null)
                ViewState["mobjRegisteredCourses"] = System.Guid.NewGuid().ToString();

            return Session[ViewState["mobjRegisteredCourses"].ToString()] as RegisteredCourses;


        }
        set
        {
            if (ViewState["mobjRegisteredCourses"] == null)
                ViewState["mobjRegisteredCourses"] = System.Guid.NewGuid().ToString();

            Session[ViewState["mobjRegisteredCourses"].ToString()] = value;
        }
    }


    public Persons mObjPersons
    {
        get
        {
            if (ViewState["mObjPersons"] == null)
                ViewState["mObjPersons"] = System.Guid.NewGuid().ToString();

            return Session[ViewState["mObjPersons"].ToString()] as Persons;


        }
        set
        {
            if (ViewState["mObjPersons"] == null)
                ViewState["mObjPersons"] = System.Guid.NewGuid().ToString();

            Session[ViewState["mObjPersons"].ToString()] = value;
        }
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            CheckSecurityAndCustomizePage();


            CheckCourseAndItsFiles();

        }

    }


    /// <summary>
    /// this function will check the security of that page
    /// </summary>
    private void CheckSecurityAndCustomizePage()
    {
        Persons currentPerson = GlobalVars.getCurrentPerson();

        mObjPersons = currentPerson;


        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Registered_courses_page))
        {
            Response.Redirect("LoginEN.aspx");
        }

        Courses courseNew = new Courses();
        try { courseNew.ID = long.Parse(Request["ID"]); }
        catch { Response.Redirect("LoginEN.aspx"); }

        if (!currentPerson.lstCourses.Contains(courseNew))
        {
            Response.Redirect("LoginEN.aspx");
        }


        List<RegisteredCourses> lstRegistered = new List<RegisteredCourses>(from obj in mObjPersons.lstRegisteredCourses where obj.objCourses.ID == courseNew.ID select obj);
        if (lstRegistered.Count == 0)
            Response.Redirect("LoginEN.aspx");

        mobjRegisteredCourses = lstRegistered[0];
    }


    /// <summary>
    /// this function will check the request for the course id and be sure that there is a course with that id
    /// </summary>
    private void CheckCourseAndItsFiles()
    {
        if (Request["ID"] == null)
        {
            Response.Redirect("loginEN.aspx");

        }

        long CourseID = -1;
        try { CourseID = long.Parse(Request["ID"]); }
        catch { Response.Redirect("loginEN.aspx"); }

        CoursesDB objCoursesDB = new CoursesDB (ConnectionStrings.LMS);

        List<Courses> lstCourses = objCoursesDB.getCoursesByID(CourseID);

        if (lstCourses.Count == 0)
        {
            Response.Redirect("loginEN.aspx");
        }


        buildCourseDir(lstCourses[0]);



    }

    
    
    
    
    /// <summary>
    /// this function will build the directory and get the toc
    /// </summary>
    /// <param name="objCourses">the course to build its directory and get its toc</param>
    private void buildCourseDir(Courses objCourses)
    {
        mObjCourses = objCourses;

        string strXmlName = GlobalVars.getCoursePath(objCourses) +  "imsmanifest.xml";


        if (!File.Exists(strXmlName))
        {
            try
            {
                if (!Directory.Exists(GlobalVars.getCoursePath(objCourses)))
                    Directory.CreateDirectory(GlobalVars.getCoursePath(objCourses));

                FastZip fz = new FastZip();
                fz.ExtractZip(Server.MapPath("./CoursesFiles/" + objCourses.Path), GlobalVars.getCoursePath(objCourses) , "");
            }
            catch
            {
               
            }
        }


            if (!File.Exists(strXmlName))
            {
                Response.Redirect("LoginEN.aspx");
                return;
            }


            List<imsitem> lstImsitem = imsitem.getListOfFile(strXmlName);
            mobjimsitemHierList = new imsitemHierList(lstImsitem);

            tv1.DataSource = mobjimsitemHierList;

            if (lstImsitem.Count > 0)
                Page.Title = lstImsitem[0].title;

            tv1.DataBind();

            
        
        
        
    }

    /// <summary>
    /// this function will set the url of nodes recursive
    /// </summary>
    /// <param name="MyNode">the node to start with</param>
    protected void setUrlOfNodes(TreeNode MyNode)
    {
        if (MyNode.NavigateUrl == "")
        {
            MyNode.NavigateUrl = getFirstNavigateUrl(MyNode);

            if (MyNode.NavigateUrl == "")
                MyNode.NavigateUrl = "#";

        }

        if (mObjCourses != null && MyNode.NavigateUrl != "#")
        {
            MyNode.NavigateUrl = GlobalVars.getCourseVirtualPath(mObjCourses) + MyNode.NavigateUrl;

        }


        foreach (TreeNode tnNew in MyNode.ChildNodes)
        {
            setUrlOfNodes(tnNew);
        }

    }



    protected void tv1_DataBound(object sender, EventArgs e)
    {

        //foreach (TreeNode tn in tv1.Nodes)
        //{
        //    setUrlOfNodes(tn);

        //}

       
    }


   

    /// <summary>
    /// this function will get the first child have navigateurl and return the url
    /// </summary>
    /// <param name="tn">the parent node</param>
    /// <returns>the navigate url of first child have one</returns>
    public string getFirstNavigateUrl(TreeNode tn)
    {
        if (tn.NavigateUrl != "")
            return tn.NavigateUrl;
        foreach (TreeNode tin in tn.ChildNodes)
        {
            string navigate = getFirstNavigateUrl(tin);
            if (navigate != "")
                return navigate;
        }

        return "";
    }

    protected void tv1_SelectedNodeChanged(object sender, EventArgs e)
    {


        imsitemHier item = getItemFromHier(mobjimsitemHierList, tv1.SelectedNode.Value);
        if (item == null)
            return;


        List<CoursesScoes> lstSocID = new List<CoursesScoes>(from obj in mobjRegisteredCourses.lstCoursesScoes where obj.ScoName == item.href select obj);

        if (lstSocID.Count == 0)
        {
            CoursesScoesDB objCoursesScoesDB = new CoursesScoesDB(ConnectionStrings.LMS);
            CoursesScoes objCoursesScoes = new CoursesScoes();
            objCoursesScoes.RegisteredCoursesID = mobjRegisteredCourses.ID;
            objCoursesScoes.IsCompleted = false;
            objCoursesScoes.ScoName = item.href;
            objCoursesScoesDB.Insert(objCoursesScoes);
        }

        lstSocID = new List<CoursesScoes>(from obj in mobjRegisteredCourses.lstCoursesScoes where obj.ScoName == item.href select obj);

        if (lstSocID.Count == 0)
            return;



        RegisteredCoursesDB objRegisteredCoursesDB = new RegisteredCoursesDB(ConnectionStrings.LMS);
        List<RegisteredCourses> lstNewRegistered = objRegisteredCoursesDB.getRegisteredCoursesByID(mobjRegisteredCourses.ID);
        if (lstNewRegistered.Count == 0)
            return;

        lstNewRegistered[0].CurrentData = tv1.SelectedNode.NavigateUrl;

        objRegisteredCoursesDB.Update(lstNewRegistered[0]);




        

        ClientScript.RegisterStartupScript(Page.GetType(), "strSetID", "window.parent.RegisteredCourses.ScoID = " + lstSocID[0].ID.ToString() + " ; window.parent.API = new LMSAPI_1484_11(); window.parent.API.MyData.deserialize ('" + lstSocID[0].ScoData.Replace("'", "\\'") + "') ; parent._MainFrame.src = '" + item.href + "' ; " , true);
    }


    /// <summary>
    /// this function will search for an item by its id
    /// </summary>
    /// <param name="lst">the list to search in</param>
    /// <param name="p">the id to search for</param>
    /// <returns>the item have the id</returns>
    private imsitemHier getItemFromHier(imsitemHierList lst, string p)
    {
        for (int i = 0; i < lst.Count; i++)
        {
            imsitemHier item = (imsitemHier)lst[i];
            if (item.id == p)
                return item;
            else
            {
                if (item.childs != null)
                {
                    imsitemHier itemNew = getItemFromHier(new imsitemHierList(item.childs), p);

                    if (itemNew != null)
                        return itemNew;
                }
            }
        }


        return null;
    }
}